package com.test;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import java.io.File;


/**
 * Created by Administrator on 2017/10/8.
 */

public class DownloadService extends Service {




    private DownloadTask  downloadTask;
    private String downloadUrl;
    private DownloaderBinder mBinder = new DownloaderBinder();

    class DownloaderBinder  extends Binder{

        public void startDownload(String url){

            if(downloadTask == null){

                downloadUrl = url;
                downloadTask =new DownloadTask(listener);
                downloadTask.execute(downloadUrl);
                startForeground(1,getNotification("Downloading ...",0));
                Toast.makeText(DownloadService.this,"Downloading.....",Toast.LENGTH_SHORT).show();
            }
        }



        public void pauseDownload(){

            if(downloadTask != null){

                downloadTask.pauseDownload();
            }
        }

        public void cancelDownload(){

            if(downloadTask != null){

                downloadTask.cancleDownload();
            }else{

                if(downloadUrl != null){

                    String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
                    String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                    File file = new File(directory+fileName);
                    if(file.exists()){

                        file.delete();
                    }
                    getNotificationManager().cancel(1);
                    stopForeground(true);
                    Toast.makeText(DownloadService.this,"Canceled",Toast.LENGTH_SHORT).show();


                }
            }
        }



    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        showNotification();
        return super.onStartCommand(intent, flags, startId);
    }

    public  void showNotification(){

        Logs.i("showNOtification");
        Intent intent = new Intent(this,MainActivity.class);
        PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);
        Notification notification = new NotificationCompat.Builder(this).setContentTitle("good morining")
                .setContentText("this is content text").setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setContentIntent(pi).build();

        startForeground(1,notification);//this is intern service
    }
    public IBinder onBind(Intent intent) {

        return mBinder;
    }

    private DownloadListener listener = new DownloadListener() {
        @Override
        public void onProgress(int progress) {
            getNotificationManager().notify(1,getNotification("downLoad.......",progress));
        }

        @Override
        public void onSuccess() {

            downloadTask = null;
            stopForeground(true);

            getNotificationManager().notify(1,getNotification("downLoad success",-1));
            Toast.makeText(DownloadService.this,"Download Success",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onFailed() {
            downloadTask = null;
            stopForeground(true);

            getNotificationManager().notify(1,getNotification("downLoad failed",-1));
            Toast.makeText(DownloadService.this,"Download failed",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onPuase() {
            downloadTask = null;
            Toast.makeText(DownloadService.this,"Download Pause",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCanceled() {
            downloadTask = null;
            stopForeground(true);
            Toast.makeText(DownloadService.this,"Download Cancled",Toast.LENGTH_SHORT).show();

        }
    };

    private NotificationManager getNotificationManager(){

        return (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    }

    private Notification getNotification(String title,int progress){

        Intent intent = new Intent(this,MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        if(progress >0){

            builder.setContentText(progress+"%");
            builder.setProgress(100,progress,false);
        }

        return builder.build();


    }


}
